# -*- coding: utf-8 -*-
# @Date   : 2020/3/3
# @File   : R12_EG_CorporationShareRatioChangeCheck_OTO.py


'''eof
name:企业法定代表人股比变更情况
code:R12_EG_CorporationShareRatioChangeCheck_OTO
tableName:
columnName:
groups:企业业务信息校验
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import re
import json
from datetime import datetime
from dateutil import relativedelta
reload(sys)
sys.setdefaultencoding('utf8')


def FormatData(tableName):
    try:
        eg = EG_DSJ.get("data").get("R1103V3")[0].get(tableName)
        return eg if isinstance(eg, list) else [{}]
    except:
        return [{}]


# 统一转成datetime对象，只能转年月日的字符串
def date_format(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date


def date_compare(before,now):
    try:
        now = date_format(now)
        before = date_format(before)
        return (now - before).days
    except:
        return None



def float_check(target):
    try:
        float(target)
        return True
    except:
        return False


null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
def getRule12():
    alterList = FormatData("alterList")
    legalPerson = ratingRequest.get("legalPerson")
    t_date = (datetime.today() - relativedelta.relativedelta(months=3)).strftime('%Y/%m/%d')

    shareHolderList = FormatData("shareHolderList")
    basic_list = FormatData("basicList")

    # 20190514新增逻辑，当为个人独资企业是通过
    if basic_list == [{}]:
        pass
    else:
        if len(basic_list) >= 1:
            enterprise_type = basic_list[0].get("enterpriseType")
            if u"个人独资企业" == enterprise_type:
                return 1

    if len(shareHolderList) >= 1 and shareHolderList != [{}]:
        nameTotal = 0
        for i in shareHolderList:
            shareholderName = i.get("shareholderName")
            if shareholderName not in null_type_list and u"公司" in shareholderName and len(shareholderName) > 5:
                nameTotal += 1
        # 20190426新增逻辑，所有股东名称全包含公司则返回1
        if len(shareHolderList) == nameTotal:
            return 1

    if alterList == [{}] or legalPerson in null_type_list:
        return u'缺失值'
    else:
        if len(alterList) >= 1:
            resultItem = None
            resultDate = None
            judgeFlag = False
            for alter in alterList:
                try:
                    altDate = alter.get("altDate")
                    altItem = alter.get("altItem")
                    altBe = alter.get("altBe")
                    altAf = alter.get("altAf")
                    bool1 = "投资人变更" in altItem or "其他变更" in altItem or "出资额变更" in altItem or "出资比例" in altItem
                    bool2 = ("投资人" in altItem and "股权" in altItem)
                    bool3 = ("投资人" in altItem and "股东" in altItem)
                    bool4 = ("出资" in altItem and "股东" in altItem)
                    if altItem not in null_type_list and (bool1 or bool2 or bool3 or bool4):
                        # 法人下标
                        indexBe = altBe.find(legalPerson) if altBe not in null_type_list else -1
                        indexAf = altAf.find(legalPerson) if altAf not in null_type_list else -1
                        if indexBe != -1 or indexAf != -1:
                            # 前后股比
                            percentBe = getPercent(altBe[indexBe:]) if indexBe != -1 else None
                            percentAf = getPercent(altAf[indexAf:]) if indexAf != -1 else None
                            diff_date = date_compare(altDate, t_date)
                            if diff_date not in null_type_list and diff_date <= 0:
                                # 变更前法人股比小于5，或者变更后法人小于5，或者前无法人，后有法人则拒绝
                                if (percentBe not in null_type_list and percentBe < 0.05) \
                                        or (percentAf not in null_type_list and percentAf < 0.05) \
                                        or (indexBe == -1 and len(altBe) > 3 and indexAf != -1):
                                    return 0
                                # 变更前无法人，变更后有法人或者股比大于5或不存在；或者前为空，后股比大于5
                                elif (indexBe == -1 and 0 < len(altBe) <= 3 and indexAf != -1 \
                                        and (percentAf is None or percentAf >= 0.05)) or \
                                        (altBe in null_type_list and indexAf != -1 and percentAf >= 0.05):
                                    judgeFlag = True
                            elif diff_date not in null_type_list and diff_date >= 0:
                                if resultDate is None and resultItem is None:
                                    resultDate = altDate
                                    resultItem = alter
                                if date_compare(resultDate, altDate) > 0:
                                    resultDate = altDate
                                    resultItem = alter
                except:
                    continue
            if judgeFlag and resultItem not in null_type_list:
                altBe = resultItem.get("altBe")
                altAf = resultItem.get("altAf")
                if altBe not in null_type_list and altBe.find(legalPerson) != -1 \
                        and altAf not in null_type_list and altAf.find(legalPerson) == -1:
                    return 0
            return 1
        else:
            return 1


def getPercent(changeItem):
    r = re.compile(r'\r|\n|\\s| ')
    changeItem = r.sub('', changeItem)
    percentList = re.findall(ur'[0-9.]+%|出资比例.?[0-9.]+%*|百分比.?[0-9.]+%*|持股比例.?[0-9.]+%*', changeItem)
    if len(percentList) > 0:
        percent = percentList[0]
        isPercent = percent.find("%")
        percent = re.findall(r'[0-9.]+', percent)
        percent = percent[0]
        try:
            percent = float(percent)
            if isPercent != -1:
                return percent/100.0
            else:
                if percent >= 1:
                    return percent/100.0
                else:
                    return percent
        except:
            return None
    else:
        return None


result = getRule12()

